//
//  RCTBridge+SourceCode.m
//  LBReact
//
//  Created by WuShiHai on 19/6/17.
//  Copyright (c) 2019 Lebbay. All rights reserved.
//

#import "RCTComponentData+Source.h"
#import "LBReactBridge.h"
#import <React/RCTBridge+Private.h>
#import <React/RCTImageSource.h>
#import <React/RCTImageView.h>

@implementation RCTComponentData(Source)

+ (void)load {
    RCTSwapInstanceMethods([RCTComponentData class],
                           @selector(setProps:forView:),
                           @selector(lb_setProps:forView:));
}

- (void)lb_setProps:(NSDictionary<NSString *, id> *)props forView:(id<RCTComponent>)view
{
    RCTBridge *bridge = [[self valueForKey:@"_bridge"] parentBridge];
    NSDictionary *defaultSource = [props objectForKey:@"defaultSource"];
    if ([view isKindOfClass:[RCTImageView class]]
        && [bridge isKindOfClass:[LBBridge class]]
        && [defaultSource isKindOfClass:[NSDictionary class]]) {
        RCTImageView *imageView = (RCTImageView *)view;
        NSString *uri = [defaultSource objectForKey:@"uri"];
        if ([uri hasPrefix:@"file:/"]) {
            NSDictionary *newProps = [NSMutableDictionary dictionaryWithDictionary:props];
            NSDictionary *newDefaultSource = [NSMutableDictionary dictionaryWithDictionary:defaultSource];
            NSURL *redirectURL = [(LBBridge *)bridge URLForAsset:[NSURL URLWithString:uri]];
            [newDefaultSource setValue:[redirectURL absoluteString] forKey:@"uri"];
            [newProps setValue:[newDefaultSource copy] forKey:@"defaultSource"];
            [self lb_setProps:[newProps copy]
                      forView:view];
        } else {
            [self lb_setProps:props
                      forView:view];
        }
        
    } else {
        [self lb_setProps:props
                  forView:view];
    }
}

@end
